package action;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

import entity.Schedule;
import entity.User;

import service.ScheduleService;
import testschedule.JsonDateValueProcessor;


public class ScheduleAction extends BaseAction {

	@Resource(name = "scheduleService")
	private ScheduleService scheduleService;
	private int id;
	private Date start;
	private Date end;
	private Schedule schedule;
	
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public Schedule getSchedule() {
		return schedule;
	}
	public void setSchedule(Schedule schedule) {
		this.schedule = schedule;
	}
	public Date getStart() {
		return start;
	}

	public void setStart(Date start) {
		this.start = start;
	}

	public Date getEnd() {
		return end;
	}

	public void setEnd(Date end) {
		this.end = end;
	}

	public ScheduleService getScheduleService() {
		return scheduleService;
	}

	public void setScheduleService(ScheduleService scheduleService) {
		this.scheduleService = scheduleService;
	}
	
	public String schedule() {
		//Do Something
		return "schedule";
	}
	public String listEvents() throws IOException {
		User user = (User)session.get("user");
		List<Schedule> schedules = (List<Schedule>)scheduleService.listEvents(user, start, end);	
		JsonConfig jsonConfig = new JsonConfig();
		  // 设置javabean中日期转换时的格式
		jsonConfig.registerJsonValueProcessor(Date.class,new JsonDateValueProcessor("yyyy-MM-dd"));
		jsonConfig.registerJsonValueProcessor(Timestamp.class,new JsonDateValueProcessor("yyyy-MM-dd hh:mm"));
		jsonConfig.setExcludes(new String[] {"user"}); //忽略字段
		response.getWriter().print(JSONArray.fromObject(schedules,jsonConfig));
		return null;
	}

	public String addEvents() throws IOException {
		User user = (User)session.get("user");
		schedule.setUser(user);
		int rid = scheduleService.addEvents(schedule);
		response.getWriter().print("[{\"id\":"+rid+"}]");
		return null;
	}
	
	public String updateEvents() {
		User user = (User)session.get("user");
		schedule.setUser(user);
		System.out.println(schedule.getRemindTime());
		scheduleService.updateEvents(schedule);
		return null;
	}
	
	public String deleteEvents() {
		scheduleService.deleteEvents(id);
		return null;
	}
}
